<template>
    <div ref="mapContainer" :style="{ width: chartWidth, height: chartHeight }"></div>
</template>

<script>
export default {
  name: 'BaiduMap',
  props:{
    chartWidth: {
      type: String,
      default: '100%'
    },
    chartHeight: {
      type: String,
      default: '100%'
    },
  },
  data() {
    return {
    };
  },
  mounted() {
    // 动态加载百度地图 API
    this.loadBaiduMapScript().then(() => {
      // 初始化地图
      this.initMap();
    });
  },
  computed: {
  },
  methods: {
    loadBaiduMapScript() {
      return new Promise((resolve, reject) => {
        if (typeof BMap !== 'undefined') {
          resolve();
        } else {
          const script = document.createElement('script');
          script.type = 'text/javascript';
          script.src = 'https://api.map.baidu.com/api?v=3.0&ak=nIgWYGIed43Q7vhBTkPyFjpaEQp4N7sL&callback=initBaiduMap';
          script.onerror = reject;
          document.head.appendChild(script);
          window.initBaiduMap = () => {
            resolve();
          };
        }
      });
    },
    initMap() {
      // 创建地图实例
      this.map = new BMap.Map(this.$refs.mapContainer, {
        coordsType: 5 // 指定坐标类型为bd09ll
      });

      // 创建点坐标
      var point = new BMap.Point(108.37426849551707, 22.81708316112129);
      // 初始化地图，设置中心点坐标和地图级别
      this.map.centerAndZoom(point, 12);
      // 开启鼠标滚轮缩放
      this.map.enableScrollWheelZoom(true);

      // 添加地图点击事件监听器
      this.map.addEventListener('click', this.handleMapClick);
    },
    handleMapClick(e) {
      // 获取点击位置的经纬度坐标
      var point = e.point;
      // 使用百度地图的逆地理编码服务获取位置信息
      var geoc = new BMap.Geocoder();
      geoc.getLocation(point, (rs) => {
        var addComp = rs.addressComponents;
        // 获取城市名和省份名详细地址
        const cityName = addComp.city;
        const provinceName = addComp.province;
        const address = rs.address;
        // 触发自定义事件，传递位置信息
        this.$emit('coordinateClicked', {
          cityName,
          provinceName,
          address,
          coordinates: `${point.lng}, ${point.lat}`
        });
      });
    }
  }
};
</script>

<style scoped>
/* 样式可以根据需要自行添加 */
</style>
